package com.example.timemanagementclock;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

	private void LoadCongViecNgayHomNay() {
		final SQLiteDatabase database = openOrCreateDatabase(
				"managertimeclock.s3db", SQLiteDatabase.CREATE_IF_NECESSARY,
				null);
		final ArrayList<Task> arrTask = new ArrayList<Task>();
		if (database != null) {
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String strCurrentDay = sdf.format(date);
			Cursor cursor = database.query("cong_viec", null,
					"ngay_thuc_hien=?", new String[] { strCurrentDay }, null,
					null, null);
			// startManagingCursor(cursor);
			if (cursor.getCount() == 0)
				Toast.makeText(MainActivity.this,
						"Bạn chưa lên lịch làm việc cho ngày hôm nay",
						Toast.LENGTH_SHORT).show();
			cursor.moveToFirst();
			int i = 1;
			while (!cursor.isAfterLast()) {
				Task task = new Task();
				task.setSTT(i);
				task.setID(cursor.getInt(0));
				task.setTenCongViec(cursor.getString(1));

				// task.setGioBatDau(cursor.getString(2));
				String dateTime = cursor.getString(2);
				sdf = new SimpleDateFormat("HH:mm");
				// Date date = new Date();
				try {
					date = sdf.parse(dateTime);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				task.setGioBatDau(date);

				// task.setGioKetThuc(cursor.getString(3));
				dateTime = cursor.getString(3);
				try {
					date = sdf.parse(dateTime);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				task.setGioKetThuc(date);

				dateTime = cursor.getString(5);
				sdf = new SimpleDateFormat("yyyy-MM-dd");
				try {
					date = sdf.parse(dateTime);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				task.setNgayLamViec(date);

				arrTask.add(task);
				cursor.moveToNext();
				i++;
			}
			cursor.close();
			final MyArrayAdapter adapter = new MyArrayAdapter(this,
					R.layout.my_item_layout, arrTask);

			ListView lvTask = (ListView) findViewById(R.id.lvTask);
			lvTask.setAdapter(adapter);
			lvTask.setItemsCanFocus(true);
			lvTask.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub

				}
			});

			lvTask.setOnItemLongClickListener(new OnItemLongClickListener() {
				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					final Task task = arrTask.get(arg2);
					final int pos = arg2;
					AlertDialog.Builder b = new Builder(MainActivity.this);
					b.setTitle("Remove");
					b.setMessage("Bạn có muốn xóa công việc này?");
					b.setIcon(R.drawable.warningicon);
					b.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									int n = database.delete("cong_viec",
											"id=?", new String[] { task.getID()
													+ "" });
									if (n > 0) {
										Toast.makeText(MainActivity.this,
												"Xóa thành công",
												Toast.LENGTH_LONG).show();

										arrTask.remove(pos);
										int stt;
										for (int i = pos; i < arrTask.size(); i++) {
											stt = arrTask.get(i).getSTT();
											arrTask.get(i).setSTT(stt - 1);
										}
										adapter.notifyDataSetChanged();
									} else {
										Toast.makeText(MainActivity.this,
												"Xóa thất bại",
												Toast.LENGTH_LONG).show();
									}
								}
							});
					b.setNegativeButton("No",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.cancel();
								}
							});
					b.show();
					adapter.notifyDataSetChanged();
					return false;
				}
			});
			adapter.notifyDataSetChanged();
		}

		ImageView ivThem = (ImageView) findViewById(R.id.ivThem);
		ivThem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent myIntent = new Intent(MainActivity.this,
						AddTaskActivity.class);
				startActivity(myIntent);
			}
		});

	}

	private void LoadCongViecTheoNgayDuocChon(String strDate) {
		final SQLiteDatabase database = openOrCreateDatabase(
				"managertimeclock.s3db", SQLiteDatabase.CREATE_IF_NECESSARY,
				null);
		final ArrayList<Task> arrTask = new ArrayList<Task>();
		if (database != null) {
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			// String strCurrentDay = sdf.format(date);
			Cursor cursor = database.query("cong_viec", null,
					"ngay_thuc_hien=?", new String[] { strDate }, null, null,
					null);
			// startManagingCursor(cursor);
			String strArrtmp[] = strDate.split("-");
			int nam = Integer.parseInt(strArrtmp[0]);
			int thang = Integer.parseInt(strArrtmp[1]);
			int ngay = Integer.parseInt(strArrtmp[2]);
			String s = ngay + "/" + thang + "/" + nam;
			if (cursor.getCount() == 0)
				Toast.makeText(MainActivity.this,
						"Bạn chưa lên lịch làm việc cho ngày " + s,
						Toast.LENGTH_SHORT).show();
			cursor.moveToFirst();
			int i = 1;
			while (!cursor.isAfterLast()) {
				Task task = new Task();
				task.setSTT(i);
				task.setID(cursor.getInt(0));
				task.setTenCongViec(cursor.getString(1));

				// task.setGioBatDau(cursor.getString(2));
				String dateTime = cursor.getString(2);
				sdf = new SimpleDateFormat("HH:mm");
				// Date date = new Date();
				try {
					date = sdf.parse(dateTime);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				task.setGioBatDau(date);

				// task.setGioKetThuc(cursor.getString(3));
				dateTime = cursor.getString(3);
				try {
					date = sdf.parse(dateTime);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				task.setGioKetThuc(date);

				dateTime = cursor.getString(5);
				sdf = new SimpleDateFormat("yyyy-MM-dd");
				try {
					date = sdf.parse(dateTime);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				task.setNgayLamViec(date);

				arrTask.add(task);
				cursor.moveToNext();
				i++;
			}
			cursor.close();
			final MyArrayAdapter adapter = new MyArrayAdapter(this,
					R.layout.my_item_layout, arrTask);

			ListView lvTask = (ListView) findViewById(R.id.lvTask);
			lvTask.setAdapter(adapter);
			lvTask.setItemsCanFocus(true);
			lvTask.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub

				}
			});

			lvTask.setOnItemLongClickListener(new OnItemLongClickListener() {
				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					final Task task = arrTask.get(arg2);
					final int pos = arg2;
					AlertDialog.Builder b = new Builder(MainActivity.this);
					b.setTitle("Remove");
					b.setMessage("Bạn có muốn xóa công việc này?");
					b.setIcon(R.drawable.warningicon);
					b.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									int n = database.delete("cong_viec",
											"id=?", new String[] { task.getID()
													+ "" });
									if (n > 0) {
										Toast.makeText(MainActivity.this,
												"Xóa thành công",
												Toast.LENGTH_SHORT).show();

										arrTask.remove(pos);
										int stt;
										for (int i = pos; i < arrTask.size(); i++) {
											stt = arrTask.get(i).getSTT();
											arrTask.get(i).setSTT(stt - 1);
										}
										adapter.notifyDataSetChanged();
									} else {
										Toast.makeText(MainActivity.this,
												"Xóa thất bại",
												Toast.LENGTH_SHORT).show();
									}
								}
							});
					b.setNegativeButton("No",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.cancel();
								}
							});
					b.show();
					adapter.notifyDataSetChanged();
					return false;
				}
			});
		}

		ImageView ivThem = (ImageView) findViewById(R.id.ivThem);
		ivThem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent myIntent = new Intent(MainActivity.this,
						AddTaskActivity.class);
				startActivity(myIntent);
			}
		});
	}

	String strDate = null;

	// TextView txtTitleDSCV = (TextView) findViewById(R.id.txtTitleDSCV); //
	// dat o day bi bao loi unfor khi chay ctrinh
	public void showDatePickerDialog() {
		OnDateSetListener callback = new OnDateSetListener() {
			// bi goi 2 lan (chua hieu tai sao->khac phuc tam thoi: gan flag =
			// false...)
			boolean flag = false; // chua goi lan nao (true: da goi roi)

			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				if (flag == false) { // neu chua goi lan nao
					flag = true; // gan da goi roi
					monthOfYear = monthOfYear + 1;
					String strYear, strMonth, strDay;
					strYear = year + "";
					if (monthOfYear < 10)
						strMonth = "0" + monthOfYear;
					else
						strMonth = monthOfYear + "";

					if (dayOfMonth < 10)
						strDay = "0" + dayOfMonth;
					else
						strDay = dayOfMonth + "";

					strDate = strYear + "-" + strMonth + "-" + strDay;
					Date date = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

					TextView txtTitleDSCV = (TextView) findViewById(R.id.txtTitleDSCV);
					if (strDate.equals(sdf.format(date))) {
						LoadCongViecNgayHomNay();
						txtTitleDSCV
								.setText("Danh sách công việc ngày hôm nay");

					} else {
						txtTitleDSCV.setText("Danh sách công việc ngày "
								+ strDay + "/" + strMonth + "/" + strYear);
						LoadCongViecTheoNgayDuocChon(strDate);
					}

				} else { // goi roi thi ko thuc hien nua
					return; // goi lan thu 2
				}
			}
		};
		// các lệnh dưới này xử lý ngày giờ trong DatePickerDialog
		// sẽ giống với trên TextView khi mở nó lên
		// String strArrtmp[] = strDate.split("/");
		// int ngay = Integer.parseInt(strArrtmp[0]);
		// int thang = Integer.parseInt(strArrtmp[1]) - 1;
		// int nam = Integer.parseInt(strArrtmp[2]);
		String strArrtmp[] = strDate.split("-");
		int nam = Integer.parseInt(strArrtmp[0]);
		int thang = Integer.parseInt(strArrtmp[1]);
		int ngay = Integer.parseInt(strArrtmp[2]);
		DatePickerDialog pic = new DatePickerDialog(this, callback, nam,
				thang - 1, ngay);
		pic.setTitle("Chọn ngày làm việc");
		pic.show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// if (savedInstanceState == null) {
		// getSupportFragmentManager().beginTransaction()
		// .add(R.id.LinearLayout1, new PlaceholderFragment())
		// .commit();
		// }
		LoadCongViecNgayHomNay();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		strDate = sdf.format(date);

		// final String strDate = null;
		Button btnHomNay = (Button) findViewById(R.id.btnHomNay);
		btnHomNay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				strDate = sdf.format(date);
				TextView txtTitleDSCV = (TextView) findViewById(R.id.txtTitleDSCV);
				txtTitleDSCV.setText("Danh sách công việc ngày hôm nay");
				LoadCongViecNgayHomNay();
			}
		});

		Button btnNgayKhac = (Button) findViewById(R.id.btnNgayKhac);
		btnNgayKhac.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDatePickerDialog();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.activity_main, container,
					false);
			return rootView;
		}
	}

}
